import { request } from '@umijs/max';
import { Button, Toast } from 'antd-mobile';
import React, { useRef, useState } from 'react';
interface FileUploadProps {
  text?: string;
  url: string;
  heades?: any;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  style?: any;
  className?: string;
}
const MUplaod: React.FC<FileUploadProps> = (props) => {
  const { text, url, heades, method = 'GET', style, className } = props;
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  const uploadFile = async (file: File) => {
    setUploading(true);
    const formData = new FormData();
    formData.append('file', file);
    try {
      const res = await request(url, {
        heades: {
          'content-type': 'multipart/form-data',
          ...heades,
        },
        method,
        data: formData,
      });
      setUploading(false);
      if (res.code === 1) {
        Toast.show({
          icon: 'success',
          content: '上传成功',
        });
        return;
      }
      Toast.show({
        icon: 'fail',
        content: JSON.stringify(res),
      });
    } catch (error) {
      console.error(error);
      setUploading(false);
    }
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      uploadFile(file);
    }
  };

  return (
    <>
      <input
        type="file"
        style={{ display: 'none' }}
        // accept="image/*"
        ref={fileInputRef}
        onChange={handleFileChange}
      />
      {uploading ? (
        <Button block size="large" style={style} className={className}>
          正在上传...
        </Button>
      ) : (
        <Button
          block
          size="large"
          style={style}
          className={className}
          onClick={() => fileInputRef.current?.click()}
        >
          {text || '选择文件'}
        </Button>
      )}
    </>
  );
};

export default MUplaod;
